<template>
  <div class="elevatorentries-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">电车进电梯预警管理系统</h1>
	            <p class="sub-title">实时监测电车进梯隐患，即时触发预警提醒，每一次及时干预，都是为电梯安全与住户平安筑起防线</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible1"
      title="编辑电梯记录"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="ruleForm" 
        :rules="rules" 
        ref="ruleFormRef" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编号" prop="entryId">
              <el-input v-model="ruleForm.entryId" placeholder="请输入唯一记录ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="带入人ID" prop="memberId">
              <el-input v-model="ruleForm.memberId" placeholder="长度3-10个字符"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="带入时间" prop="entryTime">
              <el-input v-model="ruleForm.entryTime" placeholder="请输入带入时间"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contact_info">
              <el-input v-model="ruleForm.contact_info" placeholder="请输入手机号或其他联系方式"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">确 定</el-button>
          <el-button @click="dialogVisible1 = false; resetForm()">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 搜索与操作栏 -->
    <el-row :gutter="10" style="width: 100%; margin-bottom: 20px;">
      <el-col :span="6">
        <el-input 
          placeholder="输入联系方式查询" 
          v-model="searchCondition.contact" 
          style="width: 100%;"
          @keyup.enter="handleSearch"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-input 
          placeholder="输入带入人ID查询" 
          v-model="searchCondition.memberId" 
          style="width: 100%;"
        ></el-input>
      </el-col>
      <el-col :span="2">
        <el-button 
          type="primary" 
          icon="el-icon-search" 
          @click="handleSearch" 
          style="width: 100%;"
        >
          搜索
        </el-button>
      </el-col>
      <el-col :span="2">
        <el-button 
          type="success" 
          icon="el-icon-plus" 
          @click="openDetails1()" 
          style="width: 100%;"
        >
          新增
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格与分页 -->
    <el-row style="width: 100%;">
      <el-table 
        :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
        :row-class-name="tableRowClassName"
      >
        <el-table-column fixed prop="entryId" label="编号" width="300" align="center" />
        <el-table-column prop="memberId" label="带入人ID" width="300" align="center" />
        <el-table-column prop="entryTime" label="带入时间" width="300" align="center" />
        <el-table-column prop="contact_info" label="联系方式" width="auto" align="center" />
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="warning" size="mini" icon="el-icon-edit" @click="openDetails1(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { post, get } from '@/utils/axios.js'

// 对话框控制变量
const dialogVisible1 = ref(false)

// 搜索条件
const searchCondition = reactive({
  memberId: '',    // 带入人ID查询
  contact: ''      // 联系方式查询
})

// 分页相关
const currentPage = ref(1)  // 当前页
const pageSize = ref(5)     // 每页条数
const tableData = ref([])   // 表格数据源

// 表单引用
const ruleFormRef = ref(null)   // 编辑表单引用

// 编辑表单数据
const ruleForm = reactive({
  entryId: '',
  memberId: '',
  entryTime: '',
  contact_info: ''
})

// 编辑表单验证规则
const rules = reactive({
  entryId: [
    { required: true, message: '请输入编号', trigger: 'blur' }
  ],
  memberId: [
    { required: true, message: '请输入带入人ID', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  entryTime: [
    { required: true, message: '请输入带入时间', trigger: 'blur' }
  ],
  contact_info: [
    { required: true, message: '请输入联系方式', trigger: 'blur' }
  ]
})

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1  // 重置为第一页
}
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 打开编辑对话框（编辑或新增）
const openDetails1 = (row) => {
  dialogVisible1.value = true
  if (row) {
    // 编辑已有数据
    ruleForm.entryId = row.entryId
    ruleForm.memberId = row.memberId
    ruleForm.entryTime = row.entryTime
    ruleForm.contact_info = row.contact_info
  } else {
    // 新增数据，重置表单
    resetForm()
  }
}

// 提交表单（编辑或新增）
const submitForm = () => {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return

    const loading = ElLoading.service({ text: row ? '修改中...' : '添加中...' })
    const requestUrl = row ? '/sc/elevatorentries/update' : '/sc/elevatorentries/add'
    
    post(requestUrl, ruleForm, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success(row ? '修改成功！' : '添加成功！')
        dialogVisible1.value = false
        fetchTableData()  // 重新加载表格数据
      } else {
        ElMessage.error(res.msg || (row ? '修改失败' : '添加失败'))
      }
    }, (err) => {
      loading.close()
      ElMessage.error('请求失败：' + (err.message || '网络异常'))
    })
  })
}

// 重置表单
const resetForm = () => {
  if (ruleFormRef.value) ruleFormRef.value.resetFields()
  ruleForm.entryId = ''
  ruleForm.memberId = ''
  ruleForm.entryTime = ''
  ruleForm.contact_info = ''
}

// 搜索记录
const handleSearch = () => {
  const loading = ElLoading.service({ text: '搜索中...' })
  // 构造搜索参数
  const searchParams = {
    memberId: searchCondition.memberId || null,
    contactInfo: searchCondition.contact || null
  }
  // 调用后端按条件查询接口
  post('/sc/elevatorentries/getByCondition', searchParams, (res) => {
    loading.close()
    if (res.status === 1) {
      tableData.value = res.data
      ElMessage.success(`找到 ${res.data.length} 条匹配记录`)
    } else {
      tableData.value = []
      ElMessage.warning('未找到匹配记录')
    }
  }, (err) => {
    loading.close()
    ElMessage.error('搜索失败：' + err.message)
  })
}

// 删除处理
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定删除编号为【${row.entryId}】的记录吗？删除后不可恢复`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    // 调用后端删除接口
    post('/sc/elevatorentries/deleteById', { entryId: row.entryId }, (res) => {
      loading.close()
      if (res.status === 1) {
        ElMessage.success('删除成功！')
        fetchTableData()  // 重新加载表格数据
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    }, (err) => {
      loading.close()
      ElMessage.error('删除失败：' + err.message)
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 获取所有电梯记录数据
const fetchTableData = () => {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/elevatorentries/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1) {
      tableData.value = res.data
      ElMessage.success('查询成功！')
    } else {
      ElMessage.error('未查询到数据，请重新查询')
    }
  }, (err) => {
    loading.close()
    ElMessage.error('加载失败：' + err.message)
  })
}

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  return rowIndex % 2 === 0 ? 'success-row' : ''
}

// 页面挂载时加载数据
onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.elevatorentries-container {
  width: auto;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 5px;
}

.el-table .success-row {
  background: #f0f9eb;
}




.text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.el-form-item {
  margin-bottom: 15px;
}
</style>